var chatRemote = require('../remote/chatRemote');

module.exports = function(app) {
  return new Handler(app);
};

var Handler = function(app) {
  this.app = app;
};

var handler = Handler.prototype;

/**
 * Send messages to users
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param  {Function} next next stemp callback
 *
 */
handler.send = function(msg, session, next) {
  let self = this;


  var rid = session.get('rid');
  var username = session.uid.split('*')[0];
  var channelService = this.app.get('channelService');
  let param = {
    route: 'onChat',
    msg: msg.content,
    from: username,
    target: msg.target
  };
  channel = channelService.getChannel(rid, false);

  //the target is all users
  if (msg.target == '*') {
    // 广播
    channel.pushMessage(param);
  }
  //the target is specific user
  else {
    var tuid = msg.target + '*' + rid;
    let member = channel.getMember(tuid);
    if (!member) {
      // 将消息进行缓存
      console.log('dddddddddd', msg.route)

      param = {
        route: 'offline',
        msg: msg.content,
        from: username,
        target: username
      };
      let tuid = username + '*' + rid;
      self.app.rpc.message.messageRemote.saveRecord(tuid,{},function(){});
      let tsid = channel.getMember(tuid)['sid'];
      // channelService.pushMessageByUids(param, [{
      //   uid: tuid,
      //   sid: tsid
      // }]);
    } else {
      // 推送消息
      var tsid = channel.getMember(tuid)['sid'];
      channelService.pushMessageByUids(param, [{
        uid: tuid,
        sid: tsid
      }]);
    }
  }
  next(null, {
    route: msg.route
  });
};
